package com.gw2.gw2world;

import java.util.Calendar;
import com.gw2.gw2world.controller.EventDownloader;
import com.gw2.gw2world.controller.MasterEventManager;
import com.gw2.gw2world.controller.OnTaskCompleted;
import com.gw2.gw2world.controller.Tools;
import com.gw2.gw2world.model.WorldEvent;

import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class WorldEventActivity extends Activity implements OnTaskCompleted {
	//@SuppressWarnings("unused")
	private static final String TAG="MainActivity";
	private static final long REFRESH_RATE=20000;
	SharedPreferences prefs;
	private MasterEventManager eventManager;
	private Intent intent_configuration;
	/// Use to refresh at fixed rate
	private Handler handler = new Handler();
	/// Use by the handler to refresh at fixed rate 
	private Runnable task;
	private EventDownloader downloader;
	//ui elements
	private ProgressBar pb_refreshing;
	private ListView lv_we;
	private TextView tv_done, tv_active, tv_disabled;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Tools.forceLocale(this);
		setContentView(R.layout.world_event);
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		eventManager=new MasterEventManager(this);
		lv_we=(ListView)findViewById(R.id.lv_we);
		//refresh UI
		pb_refreshing=(ProgressBar)findViewById(R.id.pb_refreshing);
		tv_done=(TextView)findViewById(R.id.tv_done);
		tv_active=(TextView)findViewById(R.id.tv_active);
		tv_disabled=(TextView)findViewById(R.id.tv_disabled);
		Tools.lockScreenFromPreferences(this);
		refreshDaily();
		refreshStatus();
		start();
	}

	private void start() {
		downloader=new EventDownloader(this,prefs.getString("language", "en"),prefs.getInt("home_server", 0),prefs.getInt("guest1_server", 0),prefs.getInt("guest2_server", 0),true);
		downloader.setWorkingView(pb_refreshing);
		downloader.setOnTaskCompletedListener(this);
		downloader.setGuesting(true);
		downloader.execute();
	}
	
	@Override
	protected void onResume() {
		Tools.lockScreenFromPreferences(this);
		refreshStatus();
		if(downloader!=null && task!=null) start();
		super.onResume();
	}
	@Override
	protected void onPause() {
		Tools.unlockScreen(this);
		if(downloader!=null) downloader.cancel(true);
		handler.removeCallbacksAndMessages(null);
		super.onPause();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId()==R.id.action_configure) {
			intent_configuration=new Intent(WorldEventActivity.this, EventConfigurationActivity.class);
			startActivity(intent_configuration);
		}
		return true;
	}
	/** Refresh the status bar: update number of active, done and disabled */
	private void refreshStatus() {
		checkDaily();
		android.util.Log.d(TAG, "refreshStatus(): ");
		tv_disabled.setText(String.valueOf(eventManager.getCountDisabled()));
		tv_active.setText(String.valueOf(eventManager.getCountActive()));
		tv_done.setText(String.valueOf(eventManager.getCountDone())+"/"+String.valueOf(eventManager.getCountAll()));
	}
	private void checkDaily() {
		final Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(prefs.getLong("last_run", System.currentTimeMillis()));
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		cal.add(Calendar.HOUR_OF_DAY, 24);
		if(cal.getTimeInMillis() >= prefs.getLong("last_run", System.currentTimeMillis())) refreshDaily();
	}
	private void refreshDaily() {
		SharedPreferences.Editor editor=prefs.edit();
		editor.putLong("last_run", System.currentTimeMillis());
		editor.commit();
		//TODO: update UI: check/uncheck events
	}
	/** Refresh UI from the processed downloaded data */
	private void refreshUI() {
		//TODO: show by event/server
		android.util.Log.d(TAG, "refreshUI(): ");
		//ll_world_event.removeAllViews();
		eventManager.refresh(downloader.getEvents());
		for(WorldEvent we : eventManager.getEvents(false)) {
			View v;
			LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); 
			v = inflater.inflate(R.layout.event_line, null);
			CheckBox cb_name=(CheckBox)v.findViewById(R.id.cb_world_event);
			cb_name.setText(we.name);
			//set server names
			for(int i=0;i<we.server_names.size();i++) {
				TextView tv;
				if(we.server_names.keyAt(i)==prefs.getInt("home_server", 0)) {
					tv=(TextView)v.findViewById(R.id.tv_server_home);
					tv.setContentDescription(we.server_names.valueAt(i));
				} else if(we.server_names.keyAt(i)==prefs.getInt("guest1_server", 0)) {
					tv=(TextView)v.findViewById(R.id.tv_server_guest1);
					tv.setContentDescription(we.server_names.valueAt(i));
				} else if(we.server_names.keyAt(i)==prefs.getInt("guest2_server", 0)) {
					tv=(TextView)v.findViewById(R.id.tv_server_guest2);
					tv.setContentDescription(we.server_names.valueAt(i));
				}
			}
			//ll_world_event.addView(v);
		}
		//ll_world_event.invalidate();
		refreshStatus();
	}
	@Override
	public void onBackPressed() {
		super.finish();
		super.onBackPressed();
	}

	@Override
	public void onTaskCompleted() {
		refreshUI();
		task = new Runnable() {
			@Override
			public void run() {start();}
		};
		handler.postDelayed(task, REFRESH_RATE);
	}
}
